<template>
  <ZForm
    ref="form"
    class="relative"
    :initial-values="initialValue"
    :rules="rules"
    #="{ cBinds, errors, resetForm }"
  >
    <div class="w-full overflow-hidden bg-base-200 px-4 py-6 lg:px-6">
      <div class="mx-auto w-full max-w-7xl">
        <div class="grid grid-cols-12 gap-y-10 md:gap-x-4">
          <!-- Featured image -->
          <div class="col-span-12 sm:col-span-5 sm:col-start-1 lg:col-span-6">
            <ZFormItem name="cover" :errors="errors">
              <ZImgInput
                class="mx-auto block w-full max-w-full rounded-2xl border-2 border-primary sm:h-[380px] sm:w-[459px] md:h-[447px] md:w-[540px]"
                alt="featured image"
                v-bind="cBinds.cover"
              >
                <div
                  class="flex h-full flex-col items-center justify-center gap-4"
                >
                  <span class="icon-[uil--image-upload] h-12 w-12"></span>
                  <h3>可以拖拽图片作为文章封面</h3>
                </div>
              </ZImgInput>
            </ZFormItem>
          </div>

          <div
            class="col-span-12 sm:col-span-6 sm:col-start-7 lg:col-span-6 lg:col-start-7"
          >
            <div class="flex h-full items-center">
              <div class="w-full max-w-md sm:mx-auto">
                <!-- Categories -->
                <div class="mb-4">
                  <div class="flex flex-wrap items-start gap-2">
                    <ZFormItem
                      class="w-full"
                      label="标签"
                      name="tags"
                      :errors="errors"
                    >
                      <ZTagSelect
                        class="w-full"
                        v-bind="cBinds.tags"
                        :data="tagsData"
                        @new-tag="onNewTag"
                      />
                    </ZFormItem>
                  </div>
                </div>
                <!-- Title -->
                <ZFormItem label="标题" name="title" :errors="errors">
                  <ZTextInput
                    class="p-2 font-sans text-3xl font-bold text-base-content"
                    v-bind="cBinds.title"
                    placeholder="请输入文章标题"
                  />
                </ZFormItem>
                <ZFormItem label="摘要" name="digest" :errors="errors">
                  <ZTextInput
                    class="w-full p-2 text-base-content/60"
                    placeholder="请输入文章摘要"
                    v-bind="cBinds.digest"
                  />
                </ZFormItem>
                <ZFormItem label="是否发布" name="published" :errors="errors">
                  <ZToggle class="toggle-primary" v-bind="cBinds.published" />
                </ZFormItem>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="w-full px-4 lg:px-6">
      <div class="mx-auto w-full max-w-5xl">
        <ZFormItem label="正文" name="content" :errors="errors">
          <ZMdEditor class="h-[36rem]" v-bind="cBinds.content" />
        </ZFormItem>
      </div>
    </div>
    <div
      class="mx-auto mb-8 flex w-full max-w-5xl justify-end gap-4 px-4 lg:px-6"
    >
      <ZButton class="btn-primary" :loading="isFetching">保存文章</ZButton>
      <ZButton type="reset" class="btn-accent" @click="resetForm()">
        重置
      </ZButton>
    </div>
  </ZForm>
</template>
<script setup lang="ts">
import { z } from "zod";
import ZForm from "@/components/forms/ZForm.vue";
import { useTagsStore } from "@/stores/tags";
import ZTextInput from "./forms/ZTextInput.vue";

interface Props {
  isFetching: boolean;
}
defineProps<Props>();

const rules = z.object({
  title: z
    .string()
    .min(3, "文章标题不能少于3个字符")
    .max(150, "文章标题不能超过150个字符"),

  cover: z.any().superRefine((val, ctx) => {
    if (!val) {
      return ctx.addIssue({
        code: z.ZodIssueCode.custom,
        message: "文章封面不能为空",
      });
    }
    const file = val as File;
    if (file.size >= 800 * 1024) {
      ctx.addIssue({
        code: z.ZodIssueCode.custom,
        message: "文章封面不能超过800KB",
      });
    }
  }),
  digest: z
    .string()
    .min(3, "文章摘要不能少于3个字符")
    .max(255, "文章摘要不能超过255个字符")
    .optional(),
  content: z.string().min(10, "文章内容不能少于10个字符"),
  published: z.boolean(),
  tags: z.array(z.number()).optional(),
});
const initialValue: z.infer<typeof rules> = {
  title: "",
  cover: null,
  digest: "",
  content: "",
  published: false,
  tags: [],
};
// 查询用户所有标签
const tagsStore = useTagsStore();
const tagsData = computed(() => {
  return tagsStore.tags.map((i) => {
    return {
      value: i.id,
      label: i.name,
    };
  });
});

// 获得 ZForm 表单实例
const form = ref<InstanceType<typeof ZForm>>();
// 新建标签
const onNewTag = async (name: string) => {
  const data = await tagsStore.newTag(name);
  if (data.value?.success) {
    // 更新表单 tags 的值
    if (form.value)
      form.value.setFieldValue("tags", [
        ...form.value.values.tags,
        data.value.object.id,
      ]);
  }
};

defineExpose({
  resetForm(state?: any, options?: any) {
    form.value?.resetForm(state, options);
  },
  setValues(values: any) {
    form.value?.setValues(values);
  },
});
</script>
